<?php

class Client_Table_Auction_Auction extends Apk_Db_Table {

    protected $_name = 'auction';
    protected $_primary = 'ID';
    public $_ERROR = "";

    public function GetError() {
        return $this->_ERROR;
    }

    public function getDataList($page = 1, $sort = null, $page_count = null, $filters = array()) {                
         $sel_inner = $this->getAdapter()->select()
                ->from($this->_name, array($this->_name . '.id', 'start_date' => "start_date"))
                ->joinLeft('auction_address', $this->_name . ".id_address = auction_address.id", array('place' => "auction_address.place"))
                ->joinLeft('dir_region', "dir_region.id = auction_address.id_region", array('region' => "dir_region.name"))
                ->joinLeft('dir_district', "dir_district.id = auction_address.id_district", array('district' => 'dir_district.name', 'district_type'=>'dir_district.type'))
                ->joinLeft('dir_town', "dir_town.id = auction_address.id_town", array('town' => "dir_town.name"))
                ->joinLeft('dir_town_type', "dir_town.town_type = dir_town_type.id", array('town_type' => "dir_town_type.shortname"))
	                ->where($this->_name . ".is_ghost = ?", 0)
	                ->where($this->_name . ".is_removed = ?", 0)
                        ->where($this->_name . ".id_status = ?", 2)
	                ->where("(select count(1) from auction_lots where auction_lots.id_auction = ".$this->_name.".id and (auction_lots.id_status = 2 or (auction_lots.id_status > 10 and auction_lots.is_approved) or auction_lots.id_status = 15)) > ?", 0);

        
        if(count($filters) > 0)
        foreach($filters as $k => $v)
        {
            switch ($k)
            {
                case 'by_id':
                    if(intval($v) > 0) $sel_inner->where("auction.id = ?", intval($v));
                    break;
                 case 'by_date':
                	if($this->checkDateFormat($v))
                		$sel_inner->where("start_date >= '".date("Y-m-d H:i:s",strtotime($v.' 00:00:00'))."' and start_date <= '".date("Y-m-d H:i:s",strtotime($v.' 23:59:59'))."'");
                	break;
                case 'from_date':
                	if($this->checkDateFormat($v))
                		$sel_inner->where("start_date > '".date("Y-m-d H:i:s",strtotime($v.' 23:59:59'))."'");
                	break;
                case 'to_date':
                	if($this->checkDateFormat($v))
                		$sel_inner->where("start_date < '".date("Y-m-d H:i:s",strtotime($v.' 00:00:00'))."'");
                	break;  
                case 'by_region':
                    if(intval($v)>0) $sel_inner->where("dir_region.id = ?", intval($v));
                    break;
                case 'by_district':
                    if(intval($v)>0) $sel_inner->where("dir_district.id = ?", intval($v));
                    break;
                case 'by_town':
                    if(intval($v)>0) $sel_inner->where("dir_town.id = ?", intval($v));
                    break;  
            }
        }   

        $pieces = preg_split("/\s/u", $sort);
        switch ($pieces[0]) {
            case 'start_date':
                $sel_inner->order("start_date " . $pieces[1]);
                break;
            case 'region':
                $sel_inner->order("region_dir.name " . $pieces[1]);
                break;
            case 'district':
                $sel_inner->order("district_dir.name " . $pieces[1]);
                break;
            case 'town':
                $sel_inner->order("town_dir.name " . $pieces[1]);
                break;
            default:
                $sel_inner->order(array("start_date DESC"));
                break;
        }

        $sel = $this->getAdapter()->select()
                ->from($sel_inner, array('id', 'start_date', 'region', 
                						'district'=>"IF(district_type='М', concat('м. ', district), district)", 
                						'town' => "concat(town_type,' ',town)", "place"));//district_type

        return $this->setDecorator('simpleDecorator')->getPager($sel, $page, array('perPage' => $page_count));
    }

    public function getDataRow($id) {
        $sel = $this->getAdapter()->select()
                ->from($this->_name, array($this->_name . ".id", 'start_date' => "to_char(start_date, 'dd.mm.yyyy hh24:mi')", $this->_name . ".id_address", 'add_date' => "to_char(" . $this->_name . ".add_date, 'dd.mm.yyyy hh24:mi')", 'modify_date' => "to_char(" . $this->_name . ".modify_date, 'dd.mm.yyyy hh24:mi')"))
                ->joinLeft('address', $this->_name . ".id_address = address.id", array('address.id_region', 'address.id_district', 'address.id_town', 'address.place'))
                ->joinLeft(array('add_account' => "accounts"), "add_account.id = " . $this->_name . ".add_user_id", array('add_user' => "add_account.last_name || ' ' || add_account.first_name || ' ' || add_account.middle_name"))
                ->joinLeft(array('modify_account' => "accounts"), "modify_account.id = " . $this->_name . ".modify_user_id", array('modify_user' => "modify_account.last_name || ' ' || modify_account.first_name || ' ' || modify_account.middle_name"))
                ->where($this->_name . ".id = ?", $id);

        return $this->getList($sel)->getRow(0)->toArray();
    }
    
	public function addressGetRegions($region_id = null) {
        $sel = $this->getAdapter()->select()
                ->from('dir_region', array('id', 'name'))
                ->order('name');

        $result = $this->setDecorator('selectDecorator')->getList($sel)->toArray();

        if (!empty($result) && isset($region_id))
            foreach ($result as $key => $value)
                if ($value['id'] == $region_id)
                    $result[$key]['__attributes']['active'] = 1;

        return $result;
    }
    
	public function addressGetDistricts($region_id = null, $district_id = null) {
        $result = array();

        if (isset($region_id)) {
            $sel = $this->getAdapter()->select()
                    ->from('dir_district', array('id', 'name' => "IF(type='М', concat('м. ', name), name)"))
                    ->where('region_id = ?', $region_id)
                    ->order("case when substr(name, 1, 3) = 'м. ' then substr(name, 4) else name end");

            $result = $this->setDecorator('selectDecorator')->getList($sel)->toArray();

            if (!empty($result) && isset($district_id))
                foreach ($result as $key => $value)
                    if ($value['id'] == $district_id)
                        $result[$key]['__attributes']['active'] = 1;
        }

        return $result;
    }

	public function addressGetTowns($region_id = null, $district_id = null, $town_id = null) {
        $result = array();

        if (isset($region_id) && isset($district_id)) {
            $sel_inner = $this->getAdapter()->select()
                    ->from('dir_town', array('dir_town.id', 'name' => "dir_town.name", 'type' => "dir_town_type.shortname"))
                    ->join('dir_town_type', "dir_town.town_type = dir_town_type.id", array())
                    ->where('dir_town.region_id = ?', $region_id)
                    ->where('dir_town.district_id = ?', $district_id)
                    ->order('name');

            $sel = $this->getAdapter()->select()
                    ->from($sel_inner, array('id', 'name' => "concat(type,' ',name)"));

            $result = $this->setDecorator('selectDecorator')->getList($sel)->toArray();

            if (!empty($result) && isset($town_id))
                foreach ($result as $key => $value)
                    if ($value['id'] == $town_id)
                        $result[$key]['__attributes']['active'] = 1;
        }

        return $result;
    }    

    public function getAuctionLotsCount($id) {
        $sel = $this->getAdapter()->select()
                ->from("lots", array('lots_count' => "count(1)"))
                ->where("id_auction = ?", $id)
                ->where("is_removed = ?", 0)
                ->where("is_ghost = ?", 0);

        return $this->getList($sel)->getRow(0)->toArray();
    }
    
    protected function auctionDecorator($key, $value) {
        switch ($key) {
            case 'start_date':
                $result[$key] = substr($value, 0,-3);
                break;

            default:
                $result[$key] = $value;
                break;
        }


        return $result;
    }
    
 public function simpleDecorator($key, $value)
    {
    	//$result[$key]='';
    	switch ($key) {
            case 'ins_date':
            case 'end_date':
            case 'deadline_date':
            case 'add_date':
            case 'modify_date':
            case 'price_date':
                if($value=="" || $value===null){
                    $result[$key] = '';
                }else{
                    $date = new DateTime($value);
                    $result[$key] = $date->format('d.m.Y');
                }
                break;
            case 'start_date':
    	 		if($value=="" || $value===null){
                    $result[$key] = '';
                }else{
                    $date = new DateTime($value);
                    $result[$key] = $date->format('d.m.Y H:i');
                }
            	break;
            case 'public_date':
            case 'archive_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;
            case 'town':
            case 'region':
            case 'district':
            	$result[$key] = $this->convertGeomNameStr($value);
            	break;
            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }

    private function checkDateFormat($str_date) {
        if (preg_match("/[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}/u", $str_date)) {
            return true;
        } else {
            return false;
        }
    }
    
	public function selectDecorator($key, $value)
    {
    	//$result[$key]='';
    	switch ($key) {
            case 'name':
            	$result[$key] = $this->convertGeomNameStr($value);
            	break;
            case 'start_date':
    	 		if($value=="" || $value===null){
                    $result[$key] = '';
                }else{
                    $date = new DateTime($value);
                    $result[$key] = $date->format('d.m.Y H:i');
                }
            	break;
            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }
    
	private function convertGeomNameStr($str, $encoding="UTF-8",$delim="."){
    	$str_prefix = "";
        $str_parts = explode(".",$str);
        if(!empty($str_parts)){
            $str = "";
            foreach ($str_parts as $part){
            	if (!(mb_strlen (trim($part) , $encoding)>2)) $str_prefix .= $part.".";
            	else {
            		if($str!="") $str .= ". "; 
            		$str .= $part;	
            	}
        	}
         	if($str_prefix!="") $str_prefix .= " ";
        }
        return $str_prefix.mb_convert_case(mb_strtolower(trim($str)), MB_CASE_TITLE, $encoding);
    }
}
